package com.mlnx.bluwifi.manager;

import com.mlnx.bluwifi.pojo.DataCache;
import com.mlnx.bluwifi.service.WifiBluService;
import com.mlnx.data.entity.SpoInfo;
import com.mlnx.device.entity.Device;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by amanda.shan on 2019/11/18.
 */
@Component
public class SpoPolicy {

    private static SpoPolicy instance = null;

    public static SpoPolicy getInstance() {
        return instance;
    }

    Map<String, Long> bluTimeMap = new HashMap<>();

    private Map<String, SpoInfo> SpoInfoMap = new ConcurrentHashMap<>();

    private Map<String, DataCache> dataCacheMap = new ConcurrentHashMap<>();

    @Autowired
    private WifiBluService wifiBluService;
    @PostConstruct
    public void init() {
        instance = this;

    }


    public boolean judge(String bluMac, int spo) {

        Long time = bluTimeMap.get(bluMac);
        if (time == null || System.currentTimeMillis() - time >= 1 * 1000) {
            bluTimeMap.put(bluMac, System.currentTimeMillis());
            return true;
        }

        return false;
    }

    public SpoInfo getSpoInfo(String deviceId) {

        SpoInfo spoInfo = SpoInfoMap.get(deviceId);
        if (spoInfo == null) {
            spoInfo = new SpoInfo();
            spoInfo.setTime(System.currentTimeMillis());
            spoInfo.setDeviceId(deviceId);
            SpoInfoMap.put(deviceId, spoInfo);
        }
        return spoInfo;
    }

    public void setSpoInfo(SpoInfo spoInfo, String deviceId) {
        SpoInfoMap.put(deviceId, spoInfo);
    }

    public DataCache getDataCache(String deviceId) {

        DataCache dataCache = dataCacheMap.get(deviceId);
        if (dataCache == null) {
            dataCache = new DataCache();
            Device device = wifiBluService.getDevice(deviceId);
            if(device!=null){
                dataCache.setDeviceType(device.getDeviceTypeId());
                dataCache.setCurrentTime(System.currentTimeMillis());
                dataCacheMap.put(deviceId, dataCache);
            }

        }
        return dataCache;
    }

    public void setDataCache(DataCache dataCache, String deviceId) {
        dataCacheMap.put(deviceId, dataCache);
    }
}
